// components/search/search.js
const app = getApp();

Component({

  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    languages: ['中文', 'English'],
    selectedLanguage: '中文',
    selectedLanguageIndex: 0,
    placeholder: '请输入商品名称或型号',
    pickerConfirmText: '确定',
    pickerCancelText: '取消',
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onLanguageChange(e) {
      const { value } = e.detail;
      const lang = Number(value) === 0 ? 'zh' : 'en';
      if (lang === app.globalData.currentLang) {
        this.setData({
          selectedLanguageIndex: Number(value),
          selectedLanguage: lang === 'zh' ? '中文' : 'English',
        });
        return;
      }
      const translations = app.switchLanguage(lang);
      this.setData({
        selectedLanguage: lang === 'zh' ? '中文' : 'English',
        selectedLanguageIndex: Number(value),
        placeholder: translations?.searchPlaceholder || this.data.placeholder,
        pickerConfirmText: translations?.pickerConfirmText || this.data.pickerConfirmText,
        pickerCancelText: translations?.pickerCancelText || this.data.pickerCancelText,
      });
      wx.request({
        url: `${app.globalData.baseUrl}/config`,
        method: 'PUT',
        data: {
          configId: 1,
          configValue: lang === 'zh' ? 'ZH' : 'en'
        },
        success: (res) => {
          console.log('res',res)
          wx.reLaunch({
            url: '/pages/index/index'
          });
        }
      })
      
    },
    onSearchInputTap() {
      // 点击搜索框跳转到搜索页面
      wx.navigateTo({
        url: '/pages/search/search'
      });
    },
    onSearch(e) {
      // 搜索框确认搜索时，跳转到搜索页面并传递关键词
      const keyword = e.detail.value;
      wx.navigateTo({
        url: `/pages/search/search?keyword=${encodeURIComponent(keyword)}`
      });
    }
  },
  lifetimes: {
    attached() {
      const lang = app.globalData.currentLang || wx.getStorageSync('language') || 'zh';
      const translations = app.globalData.lang || app.switchLanguage(lang);
      this.setData({
        selectedLanguage: lang === 'zh' ? '中文' : 'English',
        selectedLanguageIndex: lang === 'zh' ? 0 : 1,
        placeholder: translations?.searchPlaceholder || '请输入商品名称或型号',
        pickerConfirmText: translations?.pickerConfirmText || '确定',
        pickerCancelText: translations?.pickerCancelText || '取消',
      });
    }
  }
})